package xunlei1;

import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @program: gitee4_socket
 * @description:
 * @author: zy
 * @create: 2024-07-20 16:38
 */
public class DownLoadTask implements Runnable {
    private int i;
    private long fileSize;
    private int threadSize;
    private long sizePerThread;
    private String url;
    private String downloadPath;

    private static final Logger log = Logger.getLogger(DownLoadTask.class.getName());

    private DownLoadedSizeNotify dlsn;



    public DownLoadTask(int i, long fileSize, int threadSize, long sizePerThread, String url, String downloadPath,  DownLoadedSizeNotify dlsn) {
        this.i = i;
        this.fileSize = fileSize;
        this.threadSize = threadSize;
        this.sizePerThread = sizePerThread;
        this.url = url;
        this.downloadPath = downloadPath;
        this.dlsn=dlsn;

    }

    @Override
    public void run() {
        //计算此线程要下载的起始和终止位置
        long start = i * sizePerThread;
        long end = (i + 1) * sizePerThread - 1; // 最后一个线程要下载的终止位置
        RandomAccessFile raf = null;
        BufferedInputStream bis = null;
        try {
            //让RandomAccessFile 的指针偏移到这个位置
            raf = new RandomAccessFile(downloadPath, "rw");
            raf.seek(start);
            // 3. 开始下载   Range请求头
            URL u = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) u.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Range", "bytes=" + start + "-" + end);
            connection.setConnectTimeout(3000);

            connection.connect();

            bis = new BufferedInputStream(connection.getInputStream());
            byte[] bs = new byte[10 * 1024];
            int length = -1;
            while ((length = bis.read(bs, 0, bs.length)) != -1) {
                raf.write(bs, 0, length);

                log.info(Thread.currentThread().getName()+ "下载了"+length+"字节");

                if(   dlsn!=null ){
                    dlsn.notifySize(  length  );
                }
            }
            log.info(Thread.currentThread().getName()+"下载完毕:");
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("下载异常" + ex);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
